from dataclasses import dataclass, field
from datetime import datetime
from typing import List, Optional

from sqlalchemy import *
from sqlalchemy.orm import relationship

# from orm_domain import project_testcase_rel, Testcase
from orm_domain.project_testcase_rel import project_testcase_rel
from orm_domain.testcase import Testcase
from server import mapper_registry


# class Project(db.Model):
#     """项目"""
#     # 表名
#     __tablename__ = "project"
#
#     id = db.Column(db.Integer, autoincrement=True, primary_key=True, comment="项目id")
#     name = db.Column(db.String(50), nullable=False, comment="项目名称")

#     git_id = db.Column(db.Integer, default=1, comment="git_id")
#     version = db.Column(db.String(10), comment="项目版本号")
#     create_time = db.Column(db.DateTime, default=datetime.datetime.now(), comment="创建时间")
#     update_time = db.Column(db.DateTime, comment="更新时间")
#     is_del = db.Column(db.Integer, comment="是否删除 0-未删除 1-已删除")
#     #项目与用例多对多绑定
#     testcases = relationship('Testcase', backref='projects', secondary=project_testcase_rel)

@mapper_registry.mapped
@dataclass
class Project:
    __tablename__ = "project"
    __sa_dataclass_metadata_key__ = "sa"
    id: int = field(init=False, metadata={"sa": Column(Integer, primary_key=True)}, )
    name: Optional[str] = field(default=None, metadata={"sa": Column(String(120))}, )
    git_id: int = field(default=None, metadata={"sa": Column(Integer, default=1, comment="git_id")}, )
    version: Optional[str] = field(default=None, metadata={"sa": Column(String(10), comment="项目版本号")}, )

    create_time: datetime = field(default=None,
                                  metadata={"sa": Column(DateTime, nullable=True, default=datetime.now)}, )
    update_time: datetime = field(default=None,
                                  metadata={"sa": Column(DateTime, nullable=True, default=datetime.now, onupdate=datetime.now)}, )
    is_del: int = field(default=None, metadata={"sa": Column(Integer, comment="是否删除 0-未删除 1-已删除")}, )
    sign: str = field(default=None, metadata={"sa": Column(String(50), unique=True, nullable=False, comment="项目标识")})
    # 注意： 如果是List 那么default 需要修改为default_factory=list,
    testcases: List[Testcase] = field(default_factory=list, metadata={
        "sa": relationship('Testcase', backref='projects', secondary=project_testcase_rel,order_by='Testcase.update_time.desc()')}, )

